package org.jeecg.modules.xl.kuaimai.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.C;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.xl.kuaimai.KuaimaiAPIConfig;
import org.jeecg.modules.xl.kuaimai.entity.XlKuaimaiStock;
import org.jeecg.modules.xl.kuaimai.mapper.XlKuaimaiStockMapper;
import org.jeecg.modules.xl.kuaimai.vo.KCOrderCreateParam;
import org.jeecg.modules.xl.kuaimai.vo.KMStockStatusRespVO;
import org.jeecg.modules.xl.kuaimai.vo.SKUItem;
import org.jeecg.modules.xl.kuaimai.vo.SKUItemListResp;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static org.jeecg.modules.xl.kuaimai.util.RopUtils.serverSign;

/**
 * 快麦ERP的接口处理
 *
 * @author deco
 * @create 2024-11-07
 */

@Slf4j
@Service
public class KuaiMaiAPIService {
    //@Resource
    //private XlKuaimaiStockMapper xlKuaimaiStockMapper;
    /**
     * ERP商品-库存状态查询
     * 分页查询库存信息，根据返回字段的 supplierNames 是否=广州好特麦 判断是否落库
     */

    public  String flushStock() throws Exception {
        //https://open.kuaimai.com/docs/api/API%E6%96%87%E6%A1%A3/%E5%95%86%E5%93%81/%E6%9F%A5%E8%AF%A2%E5%BA%93%E5%AD%98%E7%8A%B6%E6%80%81/
        Map<String, String> firstPagePara = KuaimaiAPIConfig.getKMStockParam("100","1");

        String firstPageStr = HttpUtil.post("https://gw3.superboss.cc/router", JSON.toJSONString(firstPagePara));

        KMStockStatusRespVO FirstPagekmStockStatusResp = JSON.parseObject(firstPageStr, KMStockStatusRespVO.class);

        //System.out.println(firstPageStr);
        int total = FirstPagekmStockStatusResp.getTotal().intValue();//数据总量

        //计算总页数
        int pageTotal =  (int)Math.ceil( (double)total / 100 );

        List<XlKuaimaiStock> haotemaiStockList = new ArrayList<>();
        Map<String,String> uniKeyMap = new HashMap<>();
        //处理第一页
        //System.out.println(FirstPagekmStockStatusResp.getMsg());
        //System.out.println(FirstPagekmStockStatusResp.getTotal());
        //System.out.println(FirstPagekmStockStatusResp.getStockStatusVoList().size());
        List<XlKuaimaiStock> firstPageList = FirstPagekmStockStatusResp.getStockStatusVoList();
        for(XlKuaimaiStock  xlKuaimaiStockTemp : firstPageList){
            if(CategoryValidator.isFangziCategory(xlKuaimaiStockTemp.getCidname())){
                //如果含有纺织类，不处理
                continue;
            }
            if(uniKeyMap.containsKey(xlKuaimaiStockTemp.getMainouterid())){
                continue;
            }
            uniKeyMap.put(xlKuaimaiStockTemp.getMainouterid(),xlKuaimaiStockTemp.getMainouterid());
            xlKuaimaiStockTemp.setSltAvailableStock(xlKuaimaiStockTemp.getTotalavailablestock());
            xlKuaimaiStockTemp.setSltLockStock(0L);
            haotemaiStockList.add(xlKuaimaiStockTemp);
        }

        Thread.sleep(1000);
        //处理第二页以后
        for(int i = 2;i <= pageTotal; i++){
            log.info("处理第{}页的数据", i);
            Map<String, String> paramsTep = KuaimaiAPIConfig.getKMStockParam("100",String.valueOf(i));
            String resultJsonTemp = HttpUtil.post("https://gw3.superboss.cc/router", JSON.toJSONString(paramsTep));

            KMStockStatusRespVO kmStockStatusRespTemp = JSON.parseObject(resultJsonTemp, KMStockStatusRespVO.class);

            for(XlKuaimaiStock  xlKuaimaiStockTemp : kmStockStatusRespTemp.getStockStatusVoList()){
                if(CategoryValidator.isFangziCategory(xlKuaimaiStockTemp.getCidname())){
                    //如果含有纺织类，不处理
                    continue;
                }
                if(uniKeyMap.containsKey(xlKuaimaiStockTemp.getMainouterid())){
                    continue;
                }
                uniKeyMap.put(xlKuaimaiStockTemp.getMainouterid(),xlKuaimaiStockTemp.getMainouterid());

                xlKuaimaiStockTemp.setSltAvailableStock(xlKuaimaiStockTemp.getTotalavailablestock());
                xlKuaimaiStockTemp.setSltLockStock(0L);
                haotemaiStockList.add(xlKuaimaiStockTemp);
            }
        }

        XlKuaimaiStockMapper xlKuaimaiStockMapper =  SpringContextUtils.getBean(XlKuaimaiStockMapper.class);
        //先清空表
        xlKuaimaiStockMapper.truncate();
//        //在批量插入
//        // 先去重，避免重复 对haotemaiStockList进行去重
//        Set<String> uniqueIds = new HashSet<>();
//        List<XlKuaimaiStock> distinctList = haotemaiStockList.stream()
//                .filter(item -> uniqueIds.add(item.getMainouterid()))
//                .collect(Collectors.toList());
        xlKuaimaiStockMapper.batchInsert(haotemaiStockList);

        log.info("广州好特麦的库存流水记录有{}条，去重后有{}条",haotemaiStockList.size(),haotemaiStockList.size());
        return "";
    }

    @Async("taskExecutor")
    public CompletableFuture< List<XlKuaimaiStock>> getStockDataByPageWithAsync(String pageSize, String pageNo) throws Exception {
        Map<String, String> paramsTep = KuaimaiAPIConfig.getKMStockParam(pageSize,pageNo);

        String resultJsonTemp = HttpUtil.post("https://gw3.superboss.cc/router", JSON.toJSONString(paramsTep));

        KMStockStatusRespVO kmStockStatusRespTemp = JSON.parseObject(resultJsonTemp, KMStockStatusRespVO.class);

        List<XlKuaimaiStock> haotemaiStockList = new ArrayList<>();

//        haotemaiStockList.addAll(kmStockStatusRespTemp.getStockStatusVoList().stream().filter( xlKuaimaiStockT ->
//                ObjectUtil.isNotEmpty(xlKuaimaiStockT.getSuppliernames())&&xlKuaimaiStockT.getSuppliernames().contains("广州好特麦")
//        ).collect(Collectors.toList()));
        haotemaiStockList.addAll(kmStockStatusRespTemp.getStockStatusVoList());
        Thread.sleep(1*1000);
        log.info(Thread.currentThread().getName());
        return CompletableFuture.completedFuture(haotemaiStockList);
    }

    public String createKMOrder(KCOrderCreateParam orderCreateParam) throws Exception {
        String method = "erp.trade.create";

        Map ss = BeanUtil.beanToMap(orderCreateParam,new HashMap<>(),false,true);

        Map<String, String> paramsTep = KuaimaiAPIConfig.getKuaiMaiAPIPublicParam(method,ss);

        String resultJsonTemp = HttpUtil.post("https://gw.superboss.cc/router", JSON.toJSONString(paramsTep));

        JSONObject kmStockStatusRespTemp = JSON.parseObject(resultJsonTemp);
        System.out.println(kmStockStatusRespTemp.get("sid"));
        return resultJsonTemp;
    }

    //获取
    @Async("taskExecutor")
    public CompletableFuture< List<SKUItem>> getSKUItemListRespWithAsync(String pageSize, String pageNo) throws Exception {
        Map<String, String> paramsTep = KuaimaiAPIConfig.getSKUItemListParam(pageSize,pageNo);

        String resultJsonTemp = HttpUtil.post("https://gw3.superboss.cc/router", JSON.toJSONString(paramsTep));

        SKUItemListResp kmStockStatusRespTemp = JSON.parseObject(resultJsonTemp, SKUItemListResp.class);

        List<SKUItem> sKUItemListRespList = new ArrayList<>(kmStockStatusRespTemp.getItems());
        Thread.sleep(2*1000);
        return CompletableFuture.completedFuture(sKUItemListRespList);
    }
}

class CategoryValidator1 {

    // 使用 HashSet，查询性能 O(1)
    private static final Set<String> CATEGORY_SET = new HashSet<>();

    static {
        CATEGORY_SET.add("四季被");
        CATEGORY_SET.add("冬被");
        CATEGORY_SET.add("服装");
        CATEGORY_SET.add("被子/被芯");
        CATEGORY_SET.add("枕芯");
        CATEGORY_SET.add("床上纺织用品");
        CATEGORY_SET.add("床品套件");
        CATEGORY_SET.add("记忆棉枕芯");
        CATEGORY_SET.add("套件");
        CATEGORY_SET.add("蚊帐");
        CATEGORY_SET.add("枕巾枕套");
        CATEGORY_SET.add("三件套");
        CATEGORY_SET.add("普通床垫");
        CATEGORY_SET.add("功能性枕");
        CATEGORY_SET.add("四件套");
        CATEGORY_SET.add("夏被");
        CATEGORY_SET.add("床单");
        CATEGORY_SET.add("单被套");
        CATEGORY_SET.add("普通毛毯");
        CATEGORY_SET.add("被子");
        CATEGORY_SET.add("羽丝枕芯");
        CATEGORY_SET.add("枕芯/枕头");
        CATEGORY_SET.add("枕头");
        CATEGORY_SET.add("枕巾");
        CATEGORY_SET.add("床笠");
        CATEGORY_SET.add("毛衫");
        CATEGORY_SET.add("凉感软席");
        CATEGORY_SET.add("衣物");
        CATEGORY_SET.add("纺织用品");
        CATEGORY_SET.add("乳胶凉席");
        CATEGORY_SET.add("床头罩");
        CATEGORY_SET.add("套件枕芯");
        CATEGORY_SET.add("电热毯");
    }

    public static boolean isFangziCategory(String cidname) {
        return cidname != null && CATEGORY_SET.contains(cidname.trim());
    }
}

